<?php

namespace App\Models;

use App\Models\ComModel;

class RegionModel extends ComModel
{

    public $tablename;

    public function __construct(...$param)
    {
        parent::__construct();
        $this->tablename = 'region';
    }

    public function get_province_all()
    {
        $data = $this->db->table($this->tablename . '_province')->get()->getResultArray();
        if (!$data) {
            return ams_rt(1, '数据不存在');
        }
        $this->cache->save('province', $data, YEAR);
        return ams_rt(0, 'ok', $data);
    }

    public function get_city_all()
    {
        $data = $this->db->table($this->tablename . '_city')->get()->getResultArray();
        if (!$data) {
            return ams_rt(1, '数据不存在');
        }
        $this->cache->save('city', $data, YEAR);
        return ams_rt(0, 'ok', $data);
    }

    public function get_area_all()
    {
        $data = $this->db->table($this->tablename . '_area')->get()->getResultArray();
        if (!$data) {
            return ams_rt(1, '数据不存在');
        }
        $this->cache->save('area', $data, YEAR);
        return ams_rt(0, 'ok', $data);
    }

    public function cache_data()
    {
        $data = $this->db->table($this->tablename . '_province')->get()->getResultArray();
        if (!$data) {
            return ams_rt(1, '数据不存在');
        }
        $cache = $_city = $_area = $_province = [];
        foreach ($data as $k => $v) {
            $_province[$v['code']] = $v;
            $city = $this->db->table($this->tablename . '_city')->where('province_code', $v['code'])->get()->getResultArray();
            if ($city) {
                foreach ($city as $k1 => $v1) {
                    $_city[$v['code']][$v1['code']] = $v1;
                    $area = $this->db->table($this->tablename . '_area')->where('city_code', $v1['code'])->get()->getResultArray();
                    if ($area) {
                        foreach ($area as $k2 => $v2) {
                            $_area[$v1['code']][$v2['code']] = $v2;
                        }
                    }
                }
            }
        }

        $this->cache->save('city', $_city, YEAR);
        $this->cache->save('area', $_area, YEAR);
        $this->cache->save('province', $_province, YEAR);
        $cache = ['province' => $_province, 'city' => $_city, 'area' => $_area];
        return ams_rt(0, 'ok', $cache);
    }

}
